<script setup lang="ts">
import { Pages } from '@typings/pages'
import { ObjectUtil } from '@utils/object-util'
import { ElForm } from 'element-plus'
import { getDeviceDetailByIdAPI } from '@/api/device'
import { DeviceDTO } from '@/api/entity/device'
import YkDatePicker from '@yk/components/date-picker/YkDatePicker.vue'
import { Download } from '@element-plus/icons-vue'
import { TableUtil } from '@utils/table-util'
import YkTableColumn from '@yk/components/table-column/YkTableColumn.vue'
import YkPagination from '@yk/components/pagination/YkPagination.vue'
import {
  delShareInfoAPI,
  deviceShareByPhoneAPI,
  deviceShareByQRCodeAPI,
  editShareInfoAPI,
  getDeviceShareListByPageAPI
} from '@/api/share'
import { DeviceRoleDTO } from '@/api/entity/share'
import { ElValidator, phoneRule, required } from '@utils/form-rule'
import { FileUtil, MountedCheck } from '@/utils'
import { DeviceRoleUtil } from '@/dataset/device-role'
import { useAppStore } from '@/pinia'

defineOptions({ name: 'DeviceShare' })
const route = useRoute()
const appStore = useAppStore()

const mc = new MountedCheck()
onMounted(() => {
  DeviceRoleUtil.updateRole()
  getDeviceData()
  searchHandle()
  mc.end()
  // QRCodeRef.value.append(new AraleQRCode({
  //   text: 'y9asdfasdf',
  //   size: 100
  // }))
})

onActivated(() => {
  if (mc.isMounted()) return
  DeviceRoleUtil.updateRole()
})

// region TODO 查询
const searchParams = reactive({
  // 权限类型 0-仅查看、1-允许控制、3-可管理
  roleType: '',
  // 共享状态（0-共享中、1-已失效）
  status: '',
  // 开始时间
  startTime: '',
  // 结束时间
  endTime: '',
  // 设备列表
  deviceId: route.query.id.toString()
})
function searchHandle () {
  pages.pageNum = 1
  getTableData()
}
// endregion

// region TODO 表格数据
const pages = reactive(new Pages())
const tableData = shallowRef<DeviceRoleDTO[]>([])
function getTableData () {
  const loading = ElLoading.service()
  getDeviceShareListByPageAPI({
    ...pages.getParams(),
    param: searchParams
  }).then((res) => {
    res.result().then((rdata) => {
      tableData.value = rdata.records
      pages.total = rdata.total
    })
  })
  loading.close()
}
function delTableItem (id: string) {
  ElMessageBox.confirm('删除当前记录？', '删除提醒').then(() => {
    const loading = ElLoading.service()
    delShareInfoAPI({ id }).then(res => {
      res.result().then(() => {
        ElMessage.success('删除成功')
        getTableData()
      })
    }).finally(loading.close)
  })
}
// endregion

// region TODO 设备信息
const deviceInfo = shallowRef<DeviceDTO>({})
function getDeviceData () {
  const loading = ElLoading.service()
  getDeviceDetailByIdAPI({ id: route.query.id.toString() }).then((res) => {
    res.result().then((rdata) => {
      deviceInfo.value = rdata.data
    })
  }).finally(loading.close)
}
// endregion

// region TODO 分享
const shareSaveForm = ref({
  // 共享有效期
  expiredTime: '',
  // 权限类型 0-仅查看、1-允许控制、3-可管理
  roleType: '0',
  // 账户手机号
  phone: '',
  // 共享方式 0-手机号，1-二维码
  type: '0',
  // 二维码有效时间
  timeOutSeconds: 300
})
const shareSaveFormRef = ref<InstanceType<typeof ElForm>>()
const shareSaveFormRules = ref({
  expiredTime: [{
    validator (rule: any, value: any, callback: (error?: Error) => void) {
      const role = DeviceRoleUtil.getRole(deviceInfo.value.id)
      if (role.roleType === '3') {
        const r1 = role.expiredTime ? new Date(role.expiredTime).getTime() : Infinity
        const r2 = shareSaveForm.value.expiredTime ? new Date(shareSaveForm.value.expiredTime).getTime() : Infinity
        if (r2 > r1) {
          callback(Error('你的分享时间不能超过' + role.expiredTime))
          return
        }
      }
      callback(undefined)
    },
    trigger: 'blur'
  } as ElValidator],
  roleType: [required('共享权限为必填项')],
  type: [required('共享方式为必填项')],
  phone: [required('手机号为必填项'), phoneRule]
})
const QRCodeUrl = shallowRef('')
// 提交共享
function shareSaveSubmitHandle () {
  shareSaveFormRef.value.validate().then(() => {
    if (shareSaveForm.value.type === '0') {
      deviceShareByPhone()
    } else {
      deviceShareByQRCode()
    }
  })
}
// 手机号共享
function deviceShareByPhone () {
  deviceShareByPhoneAPI({
    deviceId: deviceInfo.value.id,
    ...shareSaveForm.value
  }).then((res) => {
    res.result().then(() => {
      ElMessage.success('设备分享成功')
    })
  })
}
// 二维码共享
function deviceShareByQRCode () {
  deviceShareByQRCodeAPI({
    deviceId: deviceInfo.value.id,
    ...shareSaveForm.value
  }).then((res) => {
    if (res.data instanceof Blob) {
      QRCodeUrl.value && URL.revokeObjectURL(QRCodeUrl.value)
      QRCodeUrl.value = URL.createObjectURL(res.data)
    }
  })
}
onBeforeUnmount(() => {
  QRCodeUrl.value && URL.revokeObjectURL(QRCodeUrl.value)
})
// endregion

// region TODO 取消分享
function unshare (id: string) {
  ElMessageBox.confirm('取消后对方将无法查看该设备，是否确定？', '取消分享').then(() => {
    const loading = ElLoading.service()
    editShareInfoAPI({ id, status: '1' }).then(res => {
      res.result().then(() => {
        ElMessage.success('已取消')
        getTableData()
      })
    }).finally(loading.close)
  })
}
// endregion

// region TODO 编辑表单 & 对话框
const shareEditForm = ref({
  id: null,
  // 共享有效期
  expiredTime: '',
  // 权限类型 0-仅查看、1-允许控制、3-可管理
  roleType: '0'
})
function shareEditSubmitHandle () {
  const loading = ElLoading.service()
  editShareInfoAPI({
    deviceId: deviceInfo.value.id,
    ...shareEditForm.value
  }).then((res) => {
    res.result().then(() => {
      ElMessage.success('保存成功')
      getTableData()
      shareSaveDialogModel.value = false
    })
  }).finally(loading.close)
}

const shareSaveDialogModel = ref(false)
function showShareSaveDialog (item: DeviceRoleDTO) {
  shareSaveDialogModel.value = true
  nextTick(() => {
    ObjectUtil.updateVal(shareEditForm.value, item)
  })
}
function closeShareSaveDialog () {
  shareSaveDialogModel.value = false
}
// endregion

</script>

<template>
  <div class="layout_view d-flex" style="min-height: 100%">
    <!--分享设备-->
    <div class="c_card-page" style="width: 432px;">
      <div class="c_card_header c_card-title bor-divider-b">分享设备</div>
      <el-form
        ref="shareSaveFormRef" :model="shareSaveForm" :rules="shareSaveFormRules"
        class="mt-16"
        label-width="130px"
      >
        <el-image
          :src="FileUtil.prefixImage(deviceInfo.url, FileUtil.DefaultImage.Device)"
          style="width: 140px;aspect-ratio: 1;" fit="contain"
        />
        <el-form-item label="设备名称：">{{ deviceInfo.deviceName }}</el-form-item>
        <el-form-item label="设备所有人：">{{ ObjectUtil.isEmptyToVal(deviceInfo.adminName, '/') }}</el-form-item>
        <el-form-item label="关联网关：">{{ deviceInfo.gatewayName }}</el-form-item>
        <el-form-item label="变量模板：">{{ deviceInfo.templateName }}</el-form-item>
        <el-form-item v-model="shareSaveForm.roleType" label="共享权限类型：" prop="roleType">
          <el-radio-group v-model="shareSaveForm.roleType">
            <el-radio label="0">仅查看</el-radio>
            <el-radio label="1">允许控制</el-radio>
            <el-radio label="3">可管理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-model="shareSaveForm.expiredTime" label="共享有效期：" prop="expiredTime" class="w-100">
          <yk-date-picker
            v-model="shareSaveForm.expiredTime" class="w-100" type="datetime"
            optional-scope="after"
            placeholder="选择共享有效期"
          />
        </el-form-item>
        <el-form-item v-if="shareSaveForm.type === '0'" label="手机号" prop="phone">
          <el-input v-model="shareSaveForm.phone" />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="shareSaveSubmitHandle">确认共享</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--设备分享列表-->
    <div v-ref-height class="c_card-page w-0 flex-1 ml-12">
      <div class="c_card_header c_card-title bor-divider-b">设备分享列表</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search mt-3" @submit.prevent="searchHandle">
        <el-form-item>
          <el-select v-model="searchParams.roleType" placeholder="全部权限" clearable>
            <el-option value="">全部</el-option>
            <el-option label="仅查看" value="0" />
            <el-option label="允许控制" value="1" />
            <el-option label="可管理" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchParams.status" placeholder="全部状态" clearable>
            <el-option value="">全部</el-option>
            <el-option label="共享中" value="0" />
            <el-option label="已失效" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <yk-date-picker v-model:start="searchParams.startTime" v-model:end="searchParams.endTime" type="datetimerange" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
      </el-form>
      <!--表格-->
      <el-table class="c_table-page w-100" stripe :data="tableData" max-height="calc(var(--ref-height) - 190px)">
        <el-table-column label="#" type="index" :index="TableUtil.indexMethod.bind(null, pages)" />
        <yk-table-column label="共享账号" prop="phone" />
        <!--<yk-table-column label="公司名称" prop="corporationName" />-->
        <yk-table-column label="权限类型" prop="roleType">
          <template #default="scope">
            {{ { 0: '仅查看', 1: '允许控制', 3: '可管理' }[scope.row.roleType] }}
          </template>
        </yk-table-column>
        <el-table-column label="共享有效期">
          <template #default="scope">{{ scope.row.expiredTime || '永久' }}</template>
        </el-table-column>
        <yk-table-column label="共享时间" prop="createdAt" sortable />
        <el-table-column label="共享状态" prop="status" sortable>
          <template #default="scope">
            <el-tag v-if="scope.row.status === '1'" type="danger" effect="light" size="small">已失效</el-tag>
            <el-tag v-else-if="scope.row.status === '0'" effect="light" size="small">共享中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template #default="scope">
            <div class="c_table-operation">
              <template v-if="scope.row.status === '0'">
                <template v-if="appStore.userInfo.id !== scope.row.userId">
                  <el-link type="primary" size="small" @click="showShareSaveDialog(scope.row)">修改</el-link>
                  <el-link type="danger" size="small" @click="unshare(scope.row.id)">取消共享</el-link>
                </template>
                <span v-else>不可操作</span>
              </template>
              <el-link v-if="scope.row.status === '1'" type="danger" size="small" @click="delTableItem(scope.row.id)">删除记录</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-affix target=".c_table-page" position="bottom" :offset="0">
        <yk-pagination class="c_table-pagination-page" :pages="pages" @handle="getTableData" />
      </el-affix>
    </div>
    <el-dialog v-model="shareSaveDialogModel" title="修改共享" width="500px" draggable>
      <el-form :model="shareEditForm" :rules="shareSaveFormRules" class="mt-16" label-width="110px">
        <el-form-item label="共享权限类型：">
          <el-radio-group v-model="shareEditForm.roleType">
            <el-radio label="0">仅查看</el-radio>
            <el-radio label="1">允许控制</el-radio>
            <el-radio label="3">可管理</el-radio>
          </el-radio-group>
          <p class="c_form-tip" style="line-height: 20px;">修改权限类型后30秒或重新进入小程序后生效，<br>网页端刷新页面生效</p>
        </el-form-item>

        <el-form-item label="共享有效期：" class="w-100 mt-3">
          <yk-date-picker
            v-model="shareEditForm.expiredTime" class="w-100" type="datetime"
            optional-scope="after" clearable
            placeholder="选择共享有效期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="c_form__submit-btn">
          <el-button type="primary" plain @click="closeShareSaveDialog">取消</el-button>
          <el-button type="primary" @click="shareEditSubmitHandle">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>
